<template>
    <div class="user-info-container">
        <h2>个人信息</h2>
        <el-card class="user-info-card">
            <template #header>
                <div class="card-header">
                    <span>基本资料</span>
                    <el-button type="primary" @click="editMode = true" v-if="!editMode">编辑</el-button>
                    <div v-else>
                        <el-button type="success" @click="saveUserInfo">保存</el-button>
                        <el-button @click="cancelEdit">取消</el-button>
                    </div>
                </div>
            </template>

            <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px" v-loading="loading">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" :disabled="!editMode || true"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userForm.name" :disabled="!editMode"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="userForm.phone" :disabled="!editMode"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userForm.sex" :disabled="!editMode">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                        <el-radio :label="0">保密</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态">
                    <el-tag :type="userForm.status === 1 ? 'success' : 'danger'">
                        {{ userForm.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="注册时间">
                    <span>{{ formatDate(userForm.createTime) }}</span>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/api/userProfile'

const userFormRef = ref(null)
const loading = ref(false)
const editMode = ref(false)

const userForm = reactive({
    id: '',
    username: '',
    name: '',
    phone: '',
    sex: 0,
    status: 1,
    createTime: ''
})

const originalUserData = ref({})

const rules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
}

// 获取用户信息
const fetchUserInfo = async () => {
    loading.value = true
    try {
        const userData = await getUserInfo()
        console.log('获取到的用户信息:', userData)

        // 使用安全的方式设置数据，避免undefined错误
        if (userData) {
            // 正确地设置表单数据
            userForm.id = userData.id || ''
            userForm.username = userData.username || ''
            userForm.name = userData.name || ''
            userForm.phone = userData.phone || ''
            userForm.sex = userData.sex || 0
            userForm.status = userData.status || 1
            userForm.createTime = userData.createTime || ''

            // 保存原始数据副本
            originalUserData.value = { ...userForm }
        } else {
            ElMessage.warning('未获取到用户信息')
        }
    } catch (error) {
        console.error('获取用户信息失败', error)
        ElMessage.error('获取用户信息失败，请稍后再试')
    } finally {
        loading.value = false
    }
}

// 保存用户信息
const saveUserInfo = () => {
    userFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                const userData = {
                    id: userForm.id,
                    name: userForm.name,
                    phone: userForm.phone,
                    sex: userForm.sex
                }
                const result = await updateUserInfo(userData)
                console.log('更新用户信息结果:', result)
                ElMessage.success('保存成功')
                editMode.value = false
                originalUserData.value = { ...userForm }

                // 刷新用户信息
                await fetchUserInfo()
            } catch (error) {
                console.error('保存用户信息失败', error)
                ElMessage.error('保存用户信息失败，请稍后再试')
            } finally {
                loading.value = false
            }
        }
    })
}

// 取消编辑
const cancelEdit = () => {
    Object.assign(userForm, originalUserData.value)
    editMode.value = false
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '未知'
    try {
        const date = new Date(dateStr)
        return date.toLocaleString()
    } catch (e) {
        console.error('日期格式化错误', e)
        return dateStr || '未知'
    }
}

onMounted(() => {
    fetchUserInfo()
})
</script>

<style scoped>
.user-info-container {
    padding: 20px;
}

.user-info-card {
    margin-top: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>